package com.sqs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.sqs.constant.ExceptionConstant;
import com.sqs.dto.KnowledgeFileInsertDTO;
import com.sqs.dto.KnowledgeFileUpdateDTO;
import com.sqs.entity.KnowledgeFile;
import com.sqs.exception.KnowledgeFileNotFoundException;
import com.sqs.mapper.KnowledgeFileMapper;
import com.sqs.service.IKnowledgeFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqs.vo.KnowledgeFileVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class KnowledgeFileServiceImpl extends ServiceImpl<KnowledgeFileMapper, KnowledgeFile> implements IKnowledgeFileService {

    @Autowired
    private KnowledgeFileMapper knowledgeFileMapper;

    /**
     * 查询知识库内所有的知识文件
     * @param repositoryId
     * @return
     */
    public List<KnowledgeFileVO> knowledgeFileSelect(Long repositoryId) {
        List<KnowledgeFile> knowledgeFiles = lambdaQuery()
                .eq(KnowledgeFile::getRepositoryId, repositoryId)
                .orderByDesc(KnowledgeFile::getCreateTime)
                .list();
        return BeanUtil.copyToList(knowledgeFiles, KnowledgeFileVO.class);
    }

    /**
     * 向知识库添加文件
     * @param knowledgeFileInsertDTO
     * @return
     * */
    public KnowledgeFileVO knowledgeFileInsert(KnowledgeFileInsertDTO knowledgeFileInsertDTO) {
        KnowledgeFile knowledgeFile = BeanUtil.copyProperties(knowledgeFileInsertDTO, KnowledgeFile.class);
        save(knowledgeFile);
        return BeanUtil.copyProperties(knowledgeFile, KnowledgeFileVO.class);
    }

    /**
     * 删除知识文件
     * @param id
     * */
    public void knowledgeFileDelete(Long id) {
        if(!lambdaQuery().eq(KnowledgeFile::getId, id).exists()){
            throw new KnowledgeFileNotFoundException(ExceptionConstant.KNOWLEDGE_FILE_NOT_FOUND);
        }
        removeById(id);
    }

    /**
     * 修改知识文件名称
     * @param knowledgeFileUpdateDTO
     * */
    public void knowledgeFileUpdate(KnowledgeFileUpdateDTO knowledgeFileUpdateDTO) {
        if(!lambdaQuery().eq(KnowledgeFile::getId, knowledgeFileUpdateDTO.getId()).exists()){
            throw new KnowledgeFileNotFoundException(ExceptionConstant.KNOWLEDGE_FILE_NOT_FOUND);
        }
        KnowledgeFile knowledgeFile = KnowledgeFile.builder()
                .id(knowledgeFileUpdateDTO.getId())
                .name(knowledgeFileUpdateDTO.getName())
                .updateTime(LocalDateTime.now())
                .build();
        updateById(knowledgeFile);
    }


}
